package com.mengtian_tech.smart_lab.service.cms;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jeecgframework.core.common.dao.impl.CommonDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tool.ImageFileTools;

import com.mengtian_tech.smart_lab.entity.cms.Attach;

@Service
public class AttachServiceImpl implements AttachService{
	@Autowired
	CommonDao dao;

	@Override
	public void updateAttachOwnerId(String ownerId, int... attachIdList) {
		String sql = "update attach set owner_id = ?  where id in (";
		List<Object> params = new ArrayList<>();
		params.add(ownerId);
		for(int i =0;i<attachIdList.length;i++){
			sql +="?";
			if(i != attachIdList.length -1) sql +=",";
			
			params.add(attachIdList[i]);
		}
		sql += ")";
		
		
		dao.executeSql(sql,params.toArray());
	}

	@Override
	public List<Attach> findAttachByOwnerId(String id) {
		return dao.findByProperty(Attach.class, "ownerId",id);
	}

	@Override
	public void deletedAttach(long[] deletedAttachList) throws IOException {
		if(deletedAttachList == null) return;
		for(long id : deletedAttachList){
			Attach a = (Attach) dao.get(Attach.class, id);
			File file = ImageFileTools.findImgFile(a.getFileName());
			if(file != null){
				file.delete();
			} 
			dao.delete(a);
		}
	}

	@Override
	public void deleteByOwnerId(String id) throws IOException{
		 List<Attach> list = dao.findByProperty(Attach.class, "ownerId",id);
		 for(Attach a : list){ 
			 if(a == null) continue;
			File file = ImageFileTools.findImgFile(a.getFileName());
			if(file != null)file.delete(); 
			dao.delete(a);
		}
	}

	@Override
	public void deletedAttach(long id) throws IOException {
		Attach a = (Attach) dao.get(Attach.class, id);
		File file = ImageFileTools.findImgFile(a.getFileName());
		if(file != null)file.delete();
		
		dao.delete(a);
	}
}
